package com.dubbo.consumer;

import com.dubbo.consumer.service.ServiceProxy;
import org.apache.curator.shaded.com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @author lihongfeng
 */
public class ConsumerApp {

    /**
     * 启动消费者端，并加载ConsumerConfig配置信息
     * @param args
     */
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfig.class);
        context.start();
        //创建代理
        ServiceProxy serviceProxy = context.getBean(ServiceProxy.class);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(50, 100
                , 0L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100)
                , new ThreadFactoryBuilder().setNameFormat("thread-pool-%d").build());
        long startTime = System.currentTimeMillis();
        int count = 0;
        //分别调用三个方法
        do {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                threadPoolExecutor.execute(() -> {
                    try {
                        serviceProxy.invokeMethod1();
                    } catch (InterruptedException e) {
                        System.out.println(e.getLocalizedMessage());
                    }
                });
                threadPoolExecutor.execute(() -> {
                    try {
                        serviceProxy.invokeMethod2();
                    } catch (InterruptedException e) {
                        System.out.println(e.getLocalizedMessage());
                    }
                });
                threadPoolExecutor.execute(() -> {
                    try {
                        serviceProxy.invokeMethod3();
                    } catch (InterruptedException e) {
                        System.out.println(e.getLocalizedMessage());
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            count++;

        } while ((System.currentTimeMillis() - startTime) <= 2 * 60 * 1000);
        System.out.println("平均每分钟调用 - " + count / 2 + " - 次");
    }


    @Configuration
    @EnableDubbo
    @PropertySource(value = "classpath:/dubbo-consumer.properties")
    @ComponentScan(basePackages = {"com.dubbo.consumer.service"})
    static class ConsumerConfig {

    }

}
